package com.cn.learn.redis.listener;

import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

/**
 * @ClassName RedisKeyExpirationListener
 * @Description TODO
 * @Author JiJiang
 * @Date 2023/6/25 23:50
 * @Version 1.0
 */
@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private RedisTemplate redisTemplate;


    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    /**
     * 针对redis数据失效事件，进行数据处理
     *
     * @param message
     * @param pattern
     */
    @Override
    public void onMessage(Message message, byte[] pattern) {
        // 用户做自己的业务处理即可,注意message.toString()可以获取失效的key
        String expiredKey = message.toString();
        Object value = redisTemplate.opsForValue().get(expiredKey);
        if (!Objects.isNull(value)) {
            System.out.println("expiredKey is ==" + expiredKey + "\t value is ==" + value.toString());
        } else {
            System.out.println("expiredKey is ==" + expiredKey + "\t value is null");
        }
    }


}
